package com.lzx.iteam.net;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.*;
import android.util.Log;
import com.lzx.iteam.CloudDialerActivity;
import com.lzx.iteam.util.Base64;
import com.lzx.iteam.util.PreferenceUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import static android.R.attr.right;

public class AsynHttpClient {

    // 内网地址
//    public static final String HTTP_API_CLIENT = "http://192.168.1.120:9000";//号码簿api
//    public static final String HTTP_API_USER_CLIENT = "http://192.168.1.120:9040";//用户api
//    public static final String HTTP_API_EVENT_CLIENT = "http://192.168.1.120:9050";//事件api
//    public static final String HTTP_API_TALK_CLIENT = "http://192.168.1.120:9090";//人脉圈api
//    public static final String HTTP_API_RONG_CHAT_CLIENT = "http://192.168.1.120:3000";//聊天api

    public static final String HTTP_API_CRM_CLIENT = "http://192.168.1.120:6100";

    public static final String HTTPS_API_USER_CLIENT = "https://iuser.ituandui.cn";//用户api

    // 外网地址
    public static final String HTTP_API_CLIENT = "http://iteam.ituandui.cn";//号码簿api
    public static final String HTTP_API_USER_CLIENT = "http://user.ituandui.cn";//用户api
    public static final String HTTP_API_EVENT_CLIENT = "http://event.ituandui.cn";//事件api
    public static final String HTTP_API_TALK_CLIENT = "http://moments.ituandui.cn";//人脉圈api
    public static final String HTTP_API_RONG_CHAT_CLIENT = "http://chat.ituandui.cn";//聊天api

    public static final String HTTP_AGREEMENT = "http://app.ituandui.cn/app/agreement"; // 使用条款
    public static final String HTTP_CONTACT_US = "http://app.ituandui.cn/app/contact"; // 联系我们

    public static final String HTTP_OPERATION_HELP = "http://app.ituandui.cn/app/help"; // 操作帮助
    public static final String HTTP_HELP_ACTION = "http://m.ituandui.cn/help/action.html ";//活动帮助
    public static final String HTTP_HELP_ANNOUNCEMENT = "http://m.ituandui.cn/help/announcement.html";//公告帮助
    public static final String HTTP_HELP_APPROVAL = "http://m.ituandui.cn/help/approval.html";//审批帮助
    public static final String HTTP_HELP_APPROVAL_ADMIN = "http://m.ituandui.cn/help/approval_admin.html";//审批人提示帮助
    public static final String HTTP_HELP_ATTENDANCE = "http://m.ituandui.cn/help/attendance.html";//考勤帮助
    public static final String HTTP_HELP_CALENDAR = "http://m.ituandui.cn/help/calendar.html";//日程安排帮助
    public static final String HTTP_HELP_CALENDAR_TABLE = "http://m.ituandui.cn/help/calendar_table.html";//日程表帮助
    public static final String HTTP_HELP_CONTACT = "http://m.ituandui.cn/help/contact.html";//联系人详情帮助
    public static final String HTTP_HELP_DRAFTS = "http://m.ituandui.cn/help/drafts.html";//草稿箱帮助
    public static final String HTTP_HELP_EVENT = "http://m.ituandui.cn/help/event.html";//事件帮助
    public static final String HTTP_HELP_FRIEND = "http://m.ituandui.cn/help/friend.html";// 人脉圈帮助
    public static final String HTTP_HELP_METTING = "http://m.ituandui.cn/help/metting.html";//会议通知帮助
    public static final String HTTP_HELP_NEW_TEAM = "http://m.ituandui.cn/help/new_team.html";//新建团队帮助
    public static final String HTTP_HELP_TAG_TIP = "http://m.ituandui.cn/help/tag_tip.html";//组织架构提示帮助
    public static final String HTTP_HELP_TEAM_MANAGE = "http://m.ituandui.cn/help/team_manage.html";// 团队管理帮助
    public static final String HTTP_HELP_VOTE = "http://m.ituandui.cn/help/vote.html";//投票帮助
    public static final String HTTP_HELP_WORK = "http://m.ituandui.cn/help/work.html";//工作平台帮助
    public static final String HTTP_HELP_APP_ATTENDANCE = "http://m.ituandui.cn/app/attendance.html";//考勤统计帮助页
    public static final String HTTP_HELP_APP_WEEKLY_MAN = "http://m.ituandui.cn/help/weekly_man.html";//周报预览人
    public static final String HTTP_HELP_APP_WEEKLY_TEMPLATE = "http://m.ituandui.cn/help/weekly_template.html";//周报模板
    public static final String HTTP_HELP_APP_WEEKLY_TIP = " http://m.ituandui.cn/help/weekly_tip.html";//周报提示

    public static final String HTTP_TEAM_DOWNLOAD = "http://ituandui.cn/download";


    private static final String TAG = "AsyncHttpClient";
    public static final int ERROR_LOCAL = 8001;
    public static final int ERROR_SERVER = 8002;
    public static final int ERROR_UNKNOWN = 8003;
    public static final int SYNC_CHANNEL_HAVE_TWOSIM_PLUGIN = 10008;

    public static final String KEY_PASS = "password";
    public static final String KEY_NEW_PASSWORD = "new_password";
    public static final String KEY_OLD_PASSWORD = "raw_password";
    public static final String KEY_RESULT_MSG = "msg";

    public static final String KEY_DEVICE_NAME = "device_name";
    public static final String KEY_DEVICE_TYPE = "device_type";
    public static final String KEY_DEVICE_NUMBER = "device_number";
    public static final String KEY_DEVICE_ID = "device_id";
    public static final String KEY_DEVICE_NO = "device_no";
    public static final String KEY_APP_VERSION = "app_version";
    public static final String KEY_CODE = "code";
    public static final String KEY_WIFI_MAC = "wifi_mac";
    public static final String KEY_WIFI = "wifi";
    public static final String KEY_SUB_FORMS = "sub_forms";
    public static final String KEY_NOON_END_TIME = "noon_end_time";
    public static final String KEY_NOON_START_TIME = "noon_start_time";

    public static final String KEY_NEW_PHONE = "phone";
    public static final String KEY_PHONE = "phone_number";
    public static final String KEY_PHONES = "users";
    public static final String KEY_NEW_USEID = "user_id";
    public static final String KEY_RONG_TOKEN = "rong_token";

    public static final String API_CONTACT_ADDLIST = "/api/contact/addlist";//批量添加联系人
    public static final String API_CONTACT_GETLIST = "/api/contact/getlist";//获取号码簿的所有联系人信息
    public static final String API_CONTACT_GET = "/api/contact/get";//获取联系人信息
    public static final String API_CONTACT_UPDATE = "/api/contact/update";//更新联系人（权限：只有管理员，创建者）本人也可编辑自己名片
    //    public static final String API_CONTACT_GETNAMECARD = "/api/contact/getnamecard";//已经移除
    public static final String API_CONTACT_SCANING = "/api/contact/add_by_scaning";//二维码扫描添加联系人
    public static final String API_CONTACT_REMOVE = "/api/contact/remove";//删除联系人
    public static final String API_CONTACT_INVITE = "/api/contact/invite";//未注册联系人邀请
    public static final String API_CONTACT_DIALCOUNT = "/api/contact/dialcount";
    public static final String API_CONTACT_NAMECARDS = "/api/contact/namecards";//点击头像获取用户在多个团队下名片信息

    public static final String API_GROUP_ADD = "/api/group/add";//创建号码簿
    public static final String API_GROUP_ADD_MANAGER = "/api/group/add_manager";//添加管理员
    public static final String API_GROUP_DELUSERS = "/api/group/delusers";//批量删除号码簿成员
    public static final String API_GROUP_GET = "/api/group/get";//获取号码簿管理员和创建者成员信息(号码簿信息app本地已经存储不用再次请求服务器，这里只给出号码簿成员信息)
    public static final String API_GROUP_REMOVE_MANAGER = "/api/group/remove_manager";//移除管理员
    //    public static final String API_GROUP_GETLIST = "/api/group/getlist";
    public static final String API_GROUP_GETLIST = "/api/group/list";//获取当前用户所有号码簿(包含演示)
    public static final String API_GROUP_REMOVE = "/api/group/remove";//解散或退出号码簿
    public static final String API_GROUP_UPDATE = "/api/group/update";//修改号码簿

    public static final String API_USER_UPGRADE = "/api/user/upgrade";//账号升级
    public static final String API_USER_VIP = "/api/user/vip";//账号等级列表
    public static final String API_USER_SYNC_MESSAGE = "/api/user/sync";//同步用户信息
    public static final String API_USER_SYNC_CONTACYS = "/api/user/sync_contacts";//同步用户本地通讯录
    public static final String API_USER_FEED = "/api/user/feed";//用户反馈
    public static final String API_USER_STATUS = "/api/user/status";
    public static final String API_USER_GOON = "/api/user/goon";//完善用户信息   用户头像七牛接口
    public static final String API_USER_IMAGE = "/api/user/image";//旧版上传头像(android接口)
    public static final String API_USER_MYNAMECARD = "/api/user/mynamecard";//查看我的名片
    public static final String API_USER_SEND_CODE = "/api/user/send_code";//注册接口发送验证码
    public static final String API_USER_SEND_CODE_PASSWORD = "/api/user/send_code_password";//忘记密码发送验证码

    public static final String API_USER_REGIST = "/api/user/register";//注册
    public static final String API_USER_LOGIN = "/api/user/login";//登录
    public static final String API_USER_RESETPASS = "/api/user/reset_pass";//重置密码
    public static final String API_USER_FORGETPASS = "/api/user/forget_pass";//忘记密码
    public static final String API_USER_LOGOUT = "/api/user/logout";//登出

    public static final String API_PERMISSION_UPGRADE_CODE = "/api/permission/upgrade_code";//升级码升级
    public static final String API_PERMISSION_GROUP_INFO = "/api/permission/group_info";//团队权限信息
    public static final String API_PERMISSION_GROUP_LIST = "/api/permission/group_list";//我的团队列表权限信息

    public static final String API_AUTH_ACCESS = "/api/auth/access";//禁止某用户进入我的个人空间
    public static final String API_AUTH_SHIELD = "/api/auth/shield";//屏蔽某人的动态
    public static final String API_AUTH_DETAIL = "/api/auth/detail";//查看我对某人权限

    public static final String API_PYS = "/api/pys";


    public static final String API_TAGS_GET = "/api/tags/get";//获取号码簿节点信息
    public static final String API_TAGS_ADD = "/api/tags/add";//添加节点
    public static final String API_TAGS_UPDATE = "/api/tags/update";//更新节点信息,如重命名
    public static final String API_TAGS_DELETE = "/api/tags/delete";//删除该节点
    public static final String API_TAGS_SET = "/api/tags/set";//设置节点下联系人(添加联系人、删除联系人都可走这个API)
    public static final String API_CONTACTS_BY_TAG = "/api/tags/contacts_by_tag";//设置节点下号码簿成员API

    public static final String API_CHATGROUP_CREATE = "/api/chatgroup/create";//创建群聊(只限注册成员，目前聊天小组成员上限200个)
    public static final String API_CHATGROUP_CREATE_SINGLE = "/api/chatgroup/create_single";//创建单聊
    public static final String API_CHATGROUP_EXIT = "/api/chatgroup/exit";//    退出或解散小组,对于成员来说是退出，对于创建者则是解散
    public static final String API_CHATGROUP_LIST = "/api/chatgroup/list";//    获取用户小组列表
    public static final String API_SYSTEM_MSG = "/api/system/msg";//    获取小秘书消息
    public static final String API_SYSTEM_LIST = "/api/system/list";//    获取小秘书消息列表


    //聊天小组详细信息--目前无需使用
    public static final String API_CHATGROUP_INFO = "/api/chatgroup/info";//    获取小组信息
    public static final String API_CHATGROUP_UPDATE = "/api/chatgroup/update";//更新聊天小组
    public static final String API_CHATGROUP_ADDMEMBER = "/api/chatgroup/add_member";//向群聊中再次添加成员  对于单聊，如果添加成员则另外生成群聊
    public static final String API_CHATGROUP_REMOVE_MEMBER = "/api/chatmember/remove";//创建者移除聊天小组成员

    public static final String API_MSG_CHAT_GETMSG = "/api/msg/get";
    public static final String API_MSG_CHAT_SEND = "/api/msg/sendg";
    public static final String API_MSG_EVENT_GETMSG = "/api/msg/get_event";
    public static final String API_MSG_CHATMSG_GETHISTORY = "/api/msg/get_history";
    public static final String API_MSG_EVENT_GET_NEW_EVENT = "/api/msg/get_new_event";

    public static final String API_EVENT_ADD = "/api/event/add";//创建公告和普通事件
    public static final String API_EVENT_ADD_MEMBERS = "/api/event/add_members";//事件添加成员(总成员最多不超过200人)
    public static final String API_EVENT_LIST = "/api/event/list";//分页获取当前用户所有事件
    public static final String API_EVENT_LIST_V2 = "/api/event/list_v2";//获取当前用户所有事件
    public static final String API_EVENT_LIST_V3 = "/api/event/list_v3";//分页获取当前用户所有事件
    public static final String API_EVENT_ADD_COMMENT = "/api/event/add_comment";//发起事件评论
    public static final String API_EVENT_GET_COMMENT = "/api/event/get_comments";//获取事件评论,活动情况，投票情况
    public static final String API_EVENT_GET = "/api/event/get";
    public static final String API_EVENT_MEMBER = "/api/event/get_members";//获取事件成员列表
    public static final String API_EVENT_REMOVE = "/api/event/remove";//退出事件
    public static final String API_EVENT_GET_TEMPLATES = "/api/event/get_templates";//获取用户事件模板
    public static final String API_EVENT_DELETE_TEMPLATES = "/api/event/del_templates";//删除自定义模板
    public static final String API_EVENT_MAKE_TEMPLATES = "/api/event/make_templates";//设置用户事件模板, 如果tmp_event_id存在则为更新模板，否则为创建模板
    public static final String API_EVENT_LIST_BY_EVENTS = "/api/event/get_list_by_events";//通过event_ids 获取当前用户对应的事件
    public static final String API_EVENT_ADD_ACTIVE = "/api/event/add_active";// 创建活动
    public static final String API_EVENT_JOIN = "/api/event/join";// 参与或不参与活动
    public static final String API_EVENT_ADD_VOTE = "/api/event/add_vote";// 创建投票
    public static final String API_EVENT_VOTE = "/api/event/vote";//参与投票
    public static final String API_EVENT_ADD_REG = "/api/event/add_reg";// 创建会议签到
    public static final String API_EVENT_CALENDAR_ADD_METTING = "/api/event/calendar/add_meeting";// 发起签到

    public static final String API_EVENT_REG = "/api/event/reg";// 签到

    public static final String API_EVENT_CALENDAR_ADD_MANAGERS = "/api/event/calendar/add_managers";// 添加日程管理员(最多不能超过5个)
    public static final String API_EVENT_CALENDAR_DEL_MANAGERS = "/api/event/calendar/del_manager";// 删除日程管理员
    public static final String API_EVENT_CALENDAR_GET_MANAGERS = "/api/event/calendar/get_managers";// 获取日程管理员
    public static final String API_EVENT_CALENDAR_GET_CALENDAR_USER = "/api/event/calendar/get_all_calendar_user";// 获取共享成员
    public static final String API_EVENT_CALENDAR_ADD = "/api/event/calendar/add";// 创建日程
    public static final String API_EVENT_CALENDAR_UPDATE = "/api/event/calendar/update";// 编辑日程
    public static final String API_EVENT_CALENDAR_DEL = "/api/event/calendar/del";// 删除日程
    public static final String API_EVENT_CALENDAR_LIST = "/api/event/calendar/list";// 日历详情
    public static final String API_EVENT_CALENDAR_STATUS = "/api/event/calendar/status";// 日历状态，"我"界面
    public static final String API_EVENT_CALENDAR_GET = "/api/event/calendar/get";// 日程请求接口(请求日程时走的接口) 消除红点
    public static final String API_EVENT_CALENDAR_DONE = "/api/event/calendar/done";// 日程完成


    public static final String API_EVENT_ATTENDANCE_GROUP_DEVICES = "/api/event/attendance/group_devices";//所有团队成员默认设备
    public static final String API_EVENT_ATTENDANCE_MY_DEVICES = "/api/event/attendance/my_devices";//我的设备
    public static final String API_EVENT_ATTENDANCE_SET_DEFAULT_DEVICES = "/api/event/attendance/set_default_devices";//设置我的默认设备
    public static final String API_EVENT_ATTENDANCE_SWITCH_SET_DEVICES = "/api/event/attendance/switch_set_device";//管理员打开或关闭成员可设置默认设备的开关
    public static final String API_EVENT_ATTENDANCE_DEVICES_STATUS = "/api/event/attendance/devices_status";//    查看某个团队成员是否更换状态
    public static final String API_EVENT_ATTENDANCE_MEMBER_LIST = "/api/event/attendance/member_list";//考勤成员列表
    public static final String API_EVENT_ATTENDANCE_SET_MEMBER_DEVIATION = "/api/event/attendance/set_member_deviation";//设置考勤成员的签到范围偏差
    public static final String API_REMOVE_ATTENDANCE_MEMBER = "/api/v3/event/attendance/remove_member";//处理重复考勤成员
    public static final String API_EVENT_ATTENDANCE_INSERT_NEW_DEFAULT_DEVICES = "/api/event/attendance/insert_new_default_devices";//插入新设备并设置成我的默认设备
    public static final String API_EVENT_ATTENDANCE_NOTIFICATION = "/api/event/attendance/notification";//考勤提醒
    public static final String API_EVENT_ATTENDANCE_GET_EXCEPTION_DEVICE = "/api/event/attendance/get_exception_device";//获取打卡异常设备
    public static final String API_EVENT_ATTENDANCE_RANKING = "/api/event/attendance/ranking";//当月考勤排行榜
    public static final String API_EVENT_ATTENDANCE_TOTAL_RANKING = "/api/event/attendance/total_ranking";//当月总工作时长考勤排行榜
    /*public static final String API_EVENT_ATTENDANCE_NEW = "/api/event/attendance/new";//创建考勤点
    public static final String API_EVENT_ATTENDANCE_UPDATE = "/api/event/attendance/update";//更新考勤点
    public static final String API_EVENT_ATTENDANCE_DEL = "/api/event/attendance/del";//删除考勤点
    public static final String API_EVENT_ATTENDANCE_USER_STATISTICS = "/api/event/attendance/user_statistics";//用户签到统计日历接口
    public static final String API_EVENT_ATTENDANCE_FACE = "/api/event/attendance/face";//用户考勤面板, 可能每个团队下有一个考勤界面，这里列出全部，客户端选择第一个展示即可。
    public static final String API_EVENT_ATTENDANCE_DO = "/api/event/attendance/do";//签到操作接口
    public static final String API_EVENT_ATTENDANCE_LIST = "/api/event/attendance/list";//考勤点列表
    public static final String API_EVENT_ATTENDANCE_ANALYSIS = "/api/event/attendance/analysis";//考勤统计
*/
    public static final String API_EVENT_ATTENDANCE_NEW = "/api/v2/event/attendance/new";//创建考勤点
    public static final String API_EVENT_ATTENDANCE_UPDATE = "/api/v2/event/attendance/update";//更新考勤点
    public static final String API_EVENT_ATTENDANCE_NEW_SUB = "/api/event/elastic/new";//创建考勤点(排班)
    public static final String API_EVENT_ATTENDANCE_UPDATE_SUB = "/api/event/elastic/update";//更新考勤点（排班）

    public static final String API_EVENT_ATTENDANCE_ELASTIC_LIST = "/api/event/elastic/list";//成员排班列表
    public static final String API_EVENT_ATTENDANCE_ELASTIC_SET = "/api/event/elastic/set";  //排班设置
    public static final String API_EVENT_ATTENDANCE_NEW_CLOCK = "/api/event/elastic/new_clock";//添加班次
    public static final String API_EVENT_ATTENDANCE_DEL_CLOCK = "/api/event/elastic/del_clock";//排班删除
    public static final String API_EVENT_ATTENDANCE_UPDATE_CLOCK = "/api/event/elastic/update_clock";//编辑班次
    public static final String API_EVENT_ATTENDANCE_ELASTIC_ME = "/api/event/elastic/me";//编辑班次


    public static final String API_EVENT_ATTENDANCE_DEL = "/api/event/attendance/del";//删除考勤点
    public static final String API_EVENT_ATTENDANCE_USER_STATISTICS = "/api/v3/event/attendance/user_statistics";//用户签到统计日历接口
    public static final String API_EVENT_ATTENDANCE_FACE = "/api/v3/event/attendance/face";//用户考勤面板, 可能每个团队下有一个考勤界面，这里列出全部，客户端选择第一个展示即可。
    public static final String API_EVENT_ATTENDANCE_DO = "/api/v3/event/attendance/do";//签到操作接口
    public static final String API_EVENT_ATTENDANCE_LIST = "/api/v3/event/attendance/list";//考勤点列表
    public static final String API_EVENT_ATTENDANCE_ANALYSIS = "/api/v3/event/attendance/analysis";//考勤统计
    public static final String API_EVENT_ATTENDANCE_FIX = "/api/event/attendance/fix";  //考勤数据修复



    public static final String API_EVENT_APPROVAL_CALENDAR = "/api/event/attendance/approval_calendar";       // 出差、请假、外出创建
    public static final String API_EVENT_APPROVAL_NEW = "/api/v2/event/approval/new";       // 出差、请假、外出创建
    public static final String API_EVENT_APPROVAL_ATTEN_STATE = "/api/v2/event/approval/atten_state";   // 审批创建
    public static final String API_EVENT_APPROVAL_CANCEL = "/api/v2/event/approval/cancel";     // 审批撤销
    public static final String API_EVENT_APPROVAL_ACTION = "/api/v2/event/approval/action";     // 审批操作

    public static final String API_EVENT_APPROVAL_DEL = "/api/event/approval/del";       // 审批删除
    public static final String API_EVENT_APPROVAL_DETAIL = "/api/event/approval/detail"; // 审批详情
    public static final String API_EVENT_APPROVAL_LIST = "/api/event/approval/list";     // 审批列表
    public static final String API_EVENT_APPROVAL_TODO = "/api/event/approval/todo";       // 审批创建
    public static final String API_APPROVAL_MAMAGER_LIST = "/api/group/approval_manager_list";  // 审批人列表
    public static final String API_APPROVAL_MAMAGER_ADD = "/api/group/add_approval_manager";  // 审批人添加
    public static final String KEY_APPROVAL_MAMAGER_REMOVE = "/api/group/remove_approval_manager";  // 审批人删除
    public static final String KEY_APPROVAL_MY_GROUPS = "/api/event/approval/my_groups";  // 审批入口,我的团队列表


    public static final String API_EVENT_WEEKLY_ALERT = "/api/event/weekly/alert"; // “我的”栏目，周报点评提醒
    public static final String API_EVENT_WEEKLY_COMMENT = "/api/event/weekly/comment"; // 评论周报
    public static final String API_EVENT_WEEKLY_DELETE = "/api/event/weekly/delete"; // 删除个人周报
    public static final String API_EVENT_WEEKLY_LIST = "/api/event/weekly/list"; // 周报列表（默认全部输出所有的年份，月份，周次，所以客户端在筛选的时候就不要在请求APi了）
    public static final String API_EVENT_WEEKLY_LIST_WEEK = "/api/event/weekly/list_week"; //  第N周周报list
    public static final String API_EVENT_WEEKLY_MY_GROUPS = "/api/event/weekly/my_groups"; // 我的团队
    public static final String API_EVENT_WEEKLY_NEW = "/api/event/weekly/new"; // 写周报,按照周报提供的模板去写
    public static final String API_EVENT_WEEKLY_EDIT = "/api/event/weekly/edit"; // 编辑周报
    public static final String API_EVENT_WEEKLY_PERMISSION_USER_ADD = "/api/event/weekly/permission_user_add"; //添加周报审查人(最多不能超过50)
    public static final String API_EVENT_WEEKLY_PERMISSION_USER_DEL = "/api/event/weekly/permission_user_del"; // 删除周报审查人
    public static final String API_EVENT_WEEKLY_PERMISSION_USER_LIST = "/api/event/weekly/permission_user_list"; // 周报审查人列表
    public static final String API_EVENT_WEEKLY_SELF = "/api/event/weekly/self"; // 我的周报(默认全部输出所有的年份，月份，周次，所以客户端在筛选的时候就不要在请求APi了。)
    public static final String API_EVENT_WEEKLY_TEMPLATE_ADD = "/api/event/weekly/template_add"; // 添加周报模板
    public static final String API_EVENT_WEEKLY_TEMPLATE_DEL = "/api/event/weekly/template_del"; // 删除周报模板
    public static final String API_EVENT_WEEKLY_TEMPLATE_LIST = "/api/event/weekly/template_list"; // 周报模板列表
    public static final String API_EVENT_WEEKLY_TEMPLATE_SET_DEFAULT = "/api/event/weekly/template_set_default"; // 设置默认周报模板
    public static final String API_EVENT_WEEKLY_TEMPLATE_UPDATE = "/api/event/weekly/template_update"; //更新周报模板
    public static final String API_EVENT_WEEKLY_DETAIL = "/api/event/weekly/detail"; //单个周报详情
    public static final String API_EVENT_WEEKLY_UNREAD_MSG = "/api/event/weekly/unread_msg"; //周报未读
    public static final String API_EVENT_LEGWORK_DO = "/api/event/legwork/do"; //外勤签到
    public static final String API_EVENT_LEGWORK_LIST = "/api/event/legwork/list"; //外勤签到列表

    public static final String API_TALK_ADD = "/api/talk/add";//创建talk。可以是纯文字，纯图片，或图文混合，但不能两者都没有
    public static final String API_TALK_ADD_COMMENT = "/api/talk/add_comment";//评论
    public static final String API_TALK_DEL = "/api/talk/del";//删除Talk
    public static final String API_TALK_DEL_REPLY = "/api/talk/del_reply";// 删除Talk评论, 只允许自己删除自己发布过的评论
    public static final String API_TALK_MSG = "/api/talk/msg";// 我的消息，消息只获取一次，已读后则服务端删除保存的消息，消息保存在本地.服务器只保存未读的消息
    public static final String API_TALK_NEW = "/api/talk/new";// "我"Tab页， 人脉圈一栏，最新Talk(包含此人头像， uid，以及与我相关的消息条数等提醒)(注意：如果是本人，则client屏蔽掉，只显示非本人的latest new).
    public static final String API_TALK_NEW_MSG_COUNT = "/api/talk/new_msg_count";// 与我相关的最新消息条数
    public static final String API_TALK_LIKE = "/api/talk/like";//点赞
    public static final String API_TALK_LIST = "/api/talk/list";//获取当前用户朋友圈列表
    public static final String API_TALK_REPLY = "/api/talk/reply";// 回复 可在评论列表中回复任何人
    public static final String API_TALK_SELF = "/api/talk/self";// 个人空间
    public static final String API_TALK_DETAIL = "/api/talk/detail";// 单个talk详情
    public static final String API_TALK_GET_TALK_TOKEN = "/api/talk/get_talk_token";//上传图片获取token，有多少key,就返回对应的token
    public static final String API_TALK_PREVIEW = "/api/talk/preview";//个人空间预览, 用于联系人详情页(如果有图片则显示最近发布的4张图片，无则什么都不显示)


    public static final String API_SALARY_MY_GROUPS = "/api/event/salary/my_groups"; //薪资入口,我的团队列表
    public static final String API_SALARY_SET_GROUP_TAX = "/api/event/salary/set_group_tax"; //获取考勤规定
    public static final String API_SALARY_GET_SALARY = "/api/event/salary/get_salary"; //获取成员基本工资和自定义字段
    public static final String API_SALARY_GET_RULE = "/api/event/salary/get_rule"; //获取考勤规定
    public static final String API_SALARY_SET_RULE = "/api/event/salary/set_rule"; // 设置考勤规定
    public static final String API_SALARY_SET_WXYJ_PC = "/api/event/salary/set_wxyj_pc"; // 五险一金
    public static final String API_SALARY_GET_WXYJ = "/api/event/salary/wxyj_list"; // 获取基数 和五险一金
    public static final String API_SALARY_SET_WXYJ_BASE = "/api/event/salary/set_wxyj_base"; // 设置养老、医疗、公积金基数
    public static final String API_SALARY_GET_ATTENDANCE_LIST = "/api/event/salary/attendance_list"; // 获取基数 和五险一金
    public static final String API_SALARY_SET_SALARY_FIELDS = "/api/event/salary/set_salary_fields"; // 设置工资字段
    public static final String API_SALARY_SET_SALARY = "/api/event/salary/set_salary"; // 设置成员基本工资 和 自定义字段薪资
    public static final String API_SALARY_SAVE = "/api/event/salary/save"; // 生成工资单
    public static final String API_SALARY_LIST_ALL = "/api/event/salary/list_all"; // 所生成的所有工资单
    public static final String API_SALARY_LIST = "/api/event/salary/list"; // 获取一个工资单
    public static final String API_SALARY_DELETE = "/api/event/salary/delete"; // 删除一个工资单



    public static final String API_QN_GET_CHAT_TOKEN = "/api/qn/get_chat_token";//用户聊天图片获取token
    public static final String API_QN_GET_US_TOKEN = "/api/qn/get_us_token";//用户上传图片获取token
    public static final String API_QN_GET_GROUP_TOKEN = "/api/qn/get_group_token";//用户上传号码簿头像获取token
    public static final String API_QN_GET_EVENT_TOKEN = "/api/qn/get_event_token";//事件上传图片获取token

    public static final String API_APP_IN = "/api/app/in";//进入app(1.关闭推送接口 2.检查socket是否连接 3.app版本检查)
    public static final String API_APP_OUT = "/api/app/out";// 进入后台,打开推送接口
    public static final String API_APP_VERSION = "/api/app/version";//检查更新
    public static final String API_APP_ANDROID_PUSH = "/api/app/android_push";//安卓设备初始化极光推送后注册registration_id

    public static final String API_CRM_PUBLIC_CREATE = "/api/crm/public/create";// 创建公海线索
    public static final String API_CRM_PUBLIC_LIST = "/api/crm/public/list";// 主页面列表
    public static final String API_CRM_PUBLIC_DEL = "/api/crm/public/del";// 删除公海线索
    public static final String API_CRM_BASE_DETAIL = "/api/crm/base/detail";//线索详情
    public static final String API_CRM_BASE_EDIT = "/api/crm/base/edit";// 编辑
    public static final String API_CRM_BASE_COMMENT = "/api/crm/base/comment";// 线索评论
    public static final String API_CRM_CHANCE_CONVERT = "/api/crm/chance/convert";// 线索转为机会
    public static final String API_CRM_CHANCE_LIST = "/api/crm/chance/list";// 机会线索列表
    public static final String API_CRM_CHANCE_DETAIL = "/api/crm/chance/detail";//  机会详情
    public static final String API_CRM_CHANCE_COMMENT = "/api/crm/chance/comment";//  机会记录
    public static final String API_CRM_CHANCE_UPDATE = "/api/crm/chance/update";// 更新销售机会
    public static final String API_CRM_CHANCE_TRANSFER = "/api/crm/chance/transfer";// 转移销售机会给其他人

    public static final String API_CRM_BASE_GET_QN_TOKEN = "/api/crm/base/get_qn_token"; // 获取token
    public static final String API_CRM_CLIENT_CREATE = "/api/crm/client/create"; // 创建客户
    public static final String API_CRM_CLIENT_CONVERT = "/api/crm/client/convert"; // 机会转客户

    public static final String API_RONG_CHAT_TOKEN = "/user/token";//获取token
    public static final String API_RONG_CHAT_USER_INFO = "/user/info";//获取指定user_id用户信息


    public static final String KEY_CC_DATA = "data";
    public static final String KEY_CC_CODE = "code";

    public static final int KEY_TYPE_CONTACT_NAME = 0;
    public static final int KEY_TYPE_CONTACT_REMARKS = 1;
    public static final String DEFAULT_PAGE_SIZE = "25";

    public static final String KEY_RESULT = "result";
    public static final String KEY_PAGESIZE = "pagesize";
    public static final String KEY_PAGEINDEX = "pageindex";
    public static final String KEY_TAG_ID = "tag_id";

    //chat and event
    public static final String KEY_MSG_IDS = "mids";
    public static final String KEY_VERIFY_CODE = "verify_code";

    public static final String KEY_CONTACT_COUNT = "contact_count";
    public static final String KEY_IS_CREATOR = "is_creator";
    public static final String KEY_CREATOR_UID = "creator_uid";
    public static final String KEY_MEMBER_COUNT = "member_count";
    public static final String KEY_UPDATE_TIME = "update_time";

    public static final String KEY_SID = "api_key";
//    public static final String KEY_SID = "sid";
    public static final String KEY_SID_OLD = "sid";
    public static final String KEY_SECURITY_KEY = "security_key";
    public static final String KEY_USER_ID = "user_id";
    public static final String KEY_SIGN = "sign";
    public static final String KEY_TIMESTAMP = "timestamp";
    public static final String KEY_VERSION = "version";

    public static final String KEY_SEX = "sex";
    public static final String KEY_RECV_USER_ID = "recv_user_id";
    public static final String KEY_SET_UID = "set_uid";
    public static final String KEY_GROUP_ID = "group_id";
    public static final String KEY_CAL_ID = "cal_id";
    public static final String KEY_GROUP_IDS = "group_ids";
    public static final String KEY_GROUP_NAME = "group_name";
    public static final String KEY_GROUP_DESC = "group_desc";
    public static final String KEY_GROUP_TYPE = "group_type";   // public = 1 (not for normal user),
    public static final String KEY_USER_TYPE = "user_type";
    public static final String KEY_GROUP_IMG = "group_img";
    public static final String KEY_IS_NEW = "is_new";
    public static final String KEY_PATH = "path";
    public static final String KEY_USER_PHONE = "user_phone";
    public static final String KEY_USER_NAME = "user_name";
    public static final String KEY_AVATAR = "avatar";
    public static final String KEY_USER_LANDLINE = "landline";
    public static final String KEY_USER_COMPANY = "company";
    public static final String KEY_DEPARTMENT = "department";
    public static final String KEY_USER_JOB = "job";
    public static final String KEY_USER_EMAIL = "email";
    public static final String KEY_USER_ADDRESS = "address";
    public static final String KEY_USER_EDIT_TYPE = "edit_type";
    public static final String KEY_USER_PHOTO = "file";

    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_TELEPHONE = "telephone";
    public static final String KEY_CONTACT_IDS = "contact_ids";
    public static final String KEY_CONTACT_USERS = "contact_users";
    public static final String KEY_USER_IDS = "user_ids";
    public static final String KEY_FAX = "fax";
    public static final String KEY_SITE = "site";
    public static final String KEY_WEIBO = "weibo";
    public static final String KEY_TRADE = "trade";
    public static final String KEY_CLIENT_LEVEL = "client_level";

    public static final String KEY_IS_CLEAR = "is_clear";
    public static final String KEY_TAG_NAME = "tag_name";
    public static final String KEY_TAG_PATH = "tag_path";
    public static final String KEY_FLAG = "flag";
    public static final String KEY_ORDER_NUM = "order_num";

    // private = 11,
    // require_verify = 12
    public static final String KEY_KEY_START_LOCATION = "key_startLocation";
    public static final String KEY_KEY_COUNT = "key_count";
    public static final String KEY_KEY_TYPE = "key_type";

    public static final String KEY_SET_USER_ID = "set_user_id";
    public static final String KEY_SET_TYPE = "set_type";
    public static final String KEY_TALK_USER_ID = "talk_user_id";


    public static final String KEY_CONTACT_ID = "contact_id";
    public static final String KEY_MANAGER_CONTACT_ID = "manager_contact_id";
    public static final String KEY_CONTACT_URL = "contact_url";
    public static final String KEY_CONTACT_IMAGE = "contact_image";
    public static final String KEY_CONTACT_NAME = "contact_name";
    public static final String KEY_CONTACT_WORK = "jobtitle";
    public static final String KEY_PHONE_PURVIEW = "phone_purview";

    public static final String KEY_CONTACT_COMPANY = "contact_company";
    public static final String KEY_CONTACT_JOB = "contact_job";
    public static final String KEY_CONTACT_EMAIL = "contact_email";
    public static final String KEY_CONTACT_CLOUD_NAMECARD = "contact_namecard";


    public static final String KEY_CONTACT_REMARKS = "contact_remarks";
    public static final String KEY_CONTACT_PHONENUMBER = "contact_phoneNumber";
    public static final String KEY_CONTACT_PHONE = "contact_phone";
    public static final String KEY_CONTACT_LANDLINE = "contact_landline";
    public static final String KEY_CONTACT_NAMECARD = "contact_namecard";
    public static final String KEY_CONTACT_DIALCOUNT = "contact_dialcount";
    public static final String KEY_CONTACTS_LIST = "contacts_list";
    public static final String KEY_CONTACTS_NUM = "contacts_num";
    public static final String KEY_CONTACT_STRUCTURE = "contact_structure";
    public static final String KEY_CONTACT_STATUS = "contact_status";
    public static final String KEY_CONTACT_SHORT_TAGS = "short_tag_name";
    public static final String KEY_CONTACT_TAGS = "contact_tags";

    public static final String KEY_IS_ALL = "is_all";
    public static final String KEY_STRUCTURE_NAME = "name";
    public static final String KEY_STRUCTURE_PID = "pid";
    public static final String KEY_STRUCTURE_PATH = "path";
    public static final String KEY_STRUCTURE_GROUP_ID = "group_id";
    public static final String KEY_STRUCTURE_ID = "id";
    public static final String KEY_STRUCTURE_CHILD_COUNT = "child_count";
    public static final String KEY_STRUCTURE_CONTACT_COUNT = "contact_count";
    public static final String KEY_HAS_TAGS = "has_tags";
    public static final String KEY_HAS_TAG = "has_tag";
    public static final String KEY_TAGS = "tags";
    public static final String KEY_TYPE = "type";  // 登录方式 0：自动，1：安卓；2.iOS；3.web
    public static final String KEY_CURRENT_CONTACT_ID = "current_contact_id";
    public static final String KEY_APPROVAL_CONTACT_ID = "approval_contact_id";
    public static final String KEY_DELETE_CONTACT_ID = "del_contact_id";

    public static final String KEY_CHAT_GROUP_ID = "chat_group_id";
    public static final String KEY_CHAT_GROUP_IMG = "chat_group_img";
    public static final String KEY_CHAT_GROUP_NAME = "chat_group_name";
    public static final String KEY_IS_MSG_NOTE = "is_msg_note";
    public static final String KEY_DEL_USER_ID = "del_user_id";

    public static final String KEY_EVENT_TYPE = "event_type";
    public static final String KEY_EVENT_TMP_ID = "event_tmp_id";
    public static final String KEY_EVENT_MEMBERS = "recv_members";
    public static final String KEY_EVENT_TITLE = "event_title";
    public static final String KEY_EVENT_CONTENT = "event_content";
    public static final String KEY_EVENT_TIME = "event_time";
    public static final String KEY_EVENT_START_TIME = "start_datetime";
    public static final String KEY_EVENT_DATE_TIME = "end_datetime";
    public static final String KEY_EVENT_IS_QRCODE = "is_qrcode";
    public static final String KEY_EVENT_ADDRESS = "event_address";
    public static final String KEY_EVENT_ATTACHMENT = "attachment";
    public static final String KEY_EVENT_INIT_TITLE = "init_title";
    public static final String KEY_EVENT_INIT_CONTENT = "content";
    public static final String KEY_EVENT_NAME = "event_templ_name";
    public static final String KEY_EVENT_AUTHOR = "author";
    public static final String KEY_TMP_EVENT_ID = "tmp_event_id";
    public static final String KEY_EVENT_TEMP_NAME = "event_temp_name";
    public static final String KEY_EVENT_CONTENTS = "event_contents";
    public static final String KEY_EVENT_UIDS = "init_recv_uids";
    public static final String KEY_EVENT_ACTIVITE_TIME = "event_date";
    public static final String KEY_EVENT_ACTIVITE_ADDRESS = "event_address";
    public static final String KEY_EVENT_VOTE_OPTION = "option";
    public static final String KEY_EVENT_VOTE_NUMBER = "max_choice_count";

    public static final String KEY_ATTACHMENT1 = "attachment_1";
    public static final String KEY_ATTACHMENT2 = "attachment_2";
    public static final String KEY_ATTACHMENT3 = "attachment_3";
    public static final String KEY_W_TYPE = "w_type";
    public static final String KEY_EVENT_ID = "event_id";
    public static final String KEY_EVENT_IDS = "event_ids";

    public static final String KEY_MANAGER = "manager";
    public static final String KEY_MANAGERS = "managers";
    public static final String KEY_BOSS_UID = "boss_uid";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_REMARK = "remark";
    public static final String KEY_UPDATE = "update";
    public static final String KEY_HIDDEN = "hidden";
    public static final String KEY_START_DATETIME = "start_datetime";
    public static final String KEY_OLD_START_DATETIME = "old_start_datetime";
    public static final String KEY_NEW_START_DATETIME = "new_start_datetime";
    public static final String KEY_END_DATETIME = "end_datetime";
    public static final String KEY_ALERT_DATETIME = "alert_datetime";


    public static final String KEY_ORIGIN = "origin";
    public static final String KEY_STATUS = "status";
    public static final String KEY_ACTIVE_TIME = "active_time";
    public static final String KEY_CREATE_TIME = "create_time";
    public static final String KEY_SORT = "sort";


    public static final String KEY_CALENDAR = "calendar";
    public static final String KEY_YEAR = "year";
    public static final String KEY_MONTH = "month";
    public static final String KEY_CALENDAR_DAY = "day";
    public static final String KEY_CALENDAR_STATUS = "status";
    public static final String KEY_CALENDAR_STATE = "state";
    public static final String KEY_CALENDAR_DATE = "month";
    public static final String KEY_CALENDAR_BOSS_UID = "boss_uid";
    public static final String KEY_CALENDAR_DONE = "done";

    public static final String KEY_ATTENDANCES = "attendances";
    public static final String KEY_ATTENDANCE_FORM_ID = "attendance_form_id";
    public static final String KEY_AT_FORM_ID = "at_form_id";
    public static final String KEY_AT_ID = "at_id";
    public static final String KEY_FORM_ID = "form_id";
    public static final String KEY_ATTENDANCE_TYPE = "attendance_type";
    public static final String KEY_FORM_TYPE = "form_type";
    public static final String KEY_LONGITUDE = "longitude";
    public static final String KEY_LATITUDE = "latitude";
    public static final String KEY_MEMBERS = "members";
    public static final String KEY_RANK = "rank";
    public static final String KEY_START_WORK_TIME = "start_work_time";
    public static final String KEY_END_WORK_TIME = "end_work_time";
    public static final String KEY_DEVIATION = "deviation";
    public static final String KEY_WORK_DATE = "work_date";
    public static final String KEY_ATTENDANCE_UID = "attendance_uid";
    public static final String KEY_ATTENDANCE_ID = "attendance_id";
    public static final String KEY_IS_OPEN = "is_open";
    public static final String KEY_ATTENDANCE_CALENDARS = "attendance_calendars";
    public static final String KEY_IS_NOTIFICATION = "is_notification";
    public static final String KEY_SUB_NAME = "sub_name";
    public static final String KEY_SUB_ID = "sub_id";
    public static final String KEY_SUB_ATTENDANCE_ID = "sub_attendance_id";
    public static final String KEY_SUB_ATTENDANCES = "sub_attendances";
    public static final String KEY_SUB_FORM_ID = "sub_form_id";
    public static final String KEY_DATE = "date";
    public static final String KEY_IS_QUARTIC = "is_quartic";


    public static final String KEY_APPROCAL_ID = "approval_id";
    public static final String KEY_APPROCAL_TYPE = "approval_type";
    public static final String KEY_APPROVAL_GROUP_ID = "approval_group_id";
    public static final String KEY_APPROVAL_LEAVE_TYPE = "approval_leave_type";
    public static final String KEY_APPROVAL_START_TIME = "approval_start_time";
    public static final String KEY_APPROVAL_START_PART = "approval_start_part";
    public static final String KEY_APPROVAL_END_TIME = "approval_end_time";
    public static final String KEY_APPROVAL_END_PART = "approval_end_part";
    public static final String KEY_APPROVAL_ADDRESS = "approval_address";
    public static final String KEY_APPROVAL_DAY = "approval_day";
    public static final String KEY_APPROVAL_DATES = "approval_dates";
    public static final String KEY_APPROVAL_HOUR = "approval_hour";
    public static final String KEY_APPROVAL_REASON = "approval_reason";
    public static final String KEY_APPROVE_ADMIN = "approve_admin";
    public static final String KEY_APPROVAL_ATTEN_RECORD_ID = "approval_atten_record_id";
    public static final String KEY_APPROVAL_ATTEN_CALENDAR_ID = "approval_atten_calendar_id";


    public static final String KEY_WEEKLY_YEAR = "weekly_year";
    public static final String KEY_WEEKLY_MONTH = "weekly_month";
    public static final String KEY_WEEK_COUNT = "week_count";
    public static final String KEY_WEEKLY_ID = "weekly_id";
    public static final String KEY_WEEK_TEMPLATE_NAME = "template_name";
    public static final String KEY_WEEK_TEMPLATE_ID = "template_id";
    public static final String KEY_WEEK_FIELDS = "fields";
    public static final String KEY_WEEK_TIME = "weekly_time";
    public static final String KEY_WEEK_CONTENT = "content";
    public static final String KEY_WEEK_REVIEWER = "reviewer";
    public static final String KEY_WEEK_REVIEWERS = "reviewers";

    public static final String KEY_MEAL_ALLOWANCE = "meal_allowance";
    public static final String KEY_BUSINESS_ALLOWANCE = "business_allowance";
    public static final String KEY_OVERTIME_ALLOWANCE = "overtime_allowance";
    public static final String KEY_LATE_FINE = "late_fine";
    public static final String KEY_LEAVE_FINE = "leave_fine";
    public static final String KEY_ABSENT_FINE = "absent_fine";
    public static final String KEY_SALARY_TAX = "salary_tax";
    public static final String KEY_SALARY_FIELDS = "fields";
    public static final String KEY_MEMBER_SALARY = "member_salary";
    public static final String KEY_STR_MONTH = "str_month";
    public static final String KEY_GROUP_SALARY = "group_salary";

    public static final String KEY_TALK_ID = "talk_id";
    public static final String KEY_TALK_ABOUT_ID = "talk_about_id";
    public static final String KEY_REPLY_UID = "reply_uid";
    public static final String KEY_REPLY_TXT = "reply_txt";


    public static final String KEY_TEXT = "text";
    public static final String KEY_CONTENT = "content";

    public static final String KEY_CLUE_ID = "clue_id";
    public static final String KEY_CHANCE_ID = "chance_id";
    public static final String KEY_CHANCE_NAME = "chance_name";
    public static final String KEY_MARKET_AMOUNT = "market_amount";
    public static final String KEY_MARKET_STAGE = "market_stage";
    public static final String KEY_STATEMENT_DATE = "statement_date";
    public static final String KEY_CHANCE_TYPE = "chance_type";
    public static final String KEY_CHANCE_SOURCE = "chance_source";
    public static final String KEY_OBJ_ID = "obj_id";
    public static final String KEY_DEST_USER_ID = "dest_user_id";
    public static final String KEY_CLIENT_NAME = "client_name";


    public static final String KEY_KEY = "key";
    public static final String KEY_IDS = "ids";
    public static final String KEY_KEYS = "keys";
    public static final String KEY_GID = "gid";
    public static final String KEY_GRP = "grp";
    public static final String KEY_CTIME = "ctime";
    public static final String KEY_CLIENT_TYPE = "client_type";

    // SHA256加密 key
    public static String __key__ = "_**!qwasxLingzhixunTeamApp@2016_";

    private static HttpClient sHttpclient;
    private static AsynHttpClient sAsynHttpClient;

    private CcMsgSender mPostSender;
    private HttpsMsgSender mHttpsSender;
    private TalkMsgSender mTalkSender;
    private EventMsgSender mEventSender;
    private UserMsgSender mUserSender;

    private CRMMsgSender mCRMSender; // 暂时注释不用

    private ConnectivityManager mCm;
    private Context mContext;

    private AsynHttpClient(Context c) {
        mContext = c;
        mCm = (ConnectivityManager) c.getSystemService(
              Context.CONNECTIVITY_SERVICE);

        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
        HttpConnectionParams.setSoTimeout(httpParams, 20000);
        /*CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mContext);
        cookieSyncManager.startSync();
        CookieStore cookieStore = new HttpClientCookieStoreProxy(HTTP_API_CLIENT);*/
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams);
        /*defaultHttpClient.setCookieStore(cookieStore);*/
        sHttpclient = defaultHttpClient;
        HandlerThread senderThread = new HandlerThread("AsyncHttpClient");
        senderThread.start();
        Looper looper = senderThread.getLooper();
        mPostSender = new CcMsgSender(looper);
        mTalkSender = new TalkMsgSender(looper);
        mUserSender = new UserMsgSender(looper);
        mEventSender = new EventMsgSender(looper);
        mHttpsSender = new HttpsMsgSender(looper);

        mCRMSender = new CRMMsgSender(looper);
    }

    public static AsynHttpClient getInstance(Context c) {
        if (sAsynHttpClient == null) {
            sAsynHttpClient = new AsynHttpClient(c);
        }
        return sAsynHttpClient;
    }


    /**
     *  号码簿
     * @param absMsg
     */
    public void execCcHttp(CcMsgStructure absMsg) {
        if (!isConnected()) {
            absMsg.onError(ERROR_LOCAL, null);
            return;
        }
        absMsg.requestType = 1;
        Message msg = mPostSender.obtainMessage();
        msg.obj = absMsg;
        msg.sendToTarget();
    }

    /**
     * 用于用户操作
     *
     * @param ccMsgStructure
     */
    public void execUserHttp(CcMsgStructure ccMsgStructure) {
        if (!isConnected()) {
            ccMsgStructure.onError(ERROR_LOCAL, null);
            return;
        }
        ccMsgStructure.requestType = 2;
        Message msg = null;
        msg = mPostSender.obtainMessage();
        /*if (ccMsgStructure.type == 2){
            msg = mHttpsSender.obtainMessage();
        } else{
            msg = mPostSender.obtainMessage();
        }*/
//        Message msg = mUserSender.obtainMessage();
        msg.obj = ccMsgStructure;
        msg.sendToTarget();
    }

    /**
     * 用于事件操作
     *
     * @param ccMsgStructure
     */
    public void execEventHttp(CcMsgStructure ccMsgStructure) {
        if (!isConnected()) {
            ccMsgStructure.onError(ERROR_LOCAL, null);
            return;
        }
        ccMsgStructure.requestType = 3;
        Message msg = mPostSender.obtainMessage();

//        Message msg = mEventSender.obtainMessage();
        msg.obj = ccMsgStructure;
        msg.sendToTarget();
    }

    /**
     * 人脉圈
     * @param absMsg
     */
    public void execTalkHttp(CcMsgStructure absMsg) {
        if (!isConnected()) {
            absMsg.onError(ERROR_LOCAL, null);
            return;
        }
        absMsg.requestType = 4;
        Message msg = mPostSender.obtainMessage();

//        Message msg = mTalkSender.obtainMessage();
        msg.obj = absMsg;
        msg.sendToTarget();
    }

    /**
     * 用于融云操作
     *
     * @param ccMsgStructure
     */
    public void execRongHttp(CcMsgStructure ccMsgStructure) {
        if (!isConnected()) {
            ccMsgStructure.onError(ERROR_LOCAL, null);
            return;
        }
        ccMsgStructure.requestType = 5;
        Message msg = mPostSender.obtainMessage();
        msg.obj = ccMsgStructure;
        msg.sendToTarget();
    }


    /**
     * 用于CRM操作
     *
     * @param absMsg
     */
    public void execCRMHttp(CcMsgStructure absMsg) {
        if (!isConnected()) {
            absMsg.onError(ERROR_LOCAL, null);
            return;
        }
        Message msg = mCRMSender.obtainMessage();
        msg.obj = absMsg;
        msg.sendToTarget();
    }

    /**
     * 获取当前程序的版本号
     */
    public static String getVersionName(Context c) {
        PackageInfo packInfo = null;
        try {
            packInfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return (packInfo != null ? packInfo.versionName : "?");
    }


    private boolean isConnected() {
        NetworkInfo info = mCm.getActiveNetworkInfo();
        if (info == null) return false;
        return info.isConnected();
    }

    public static StringEntity entity = null;


     class CcMsgSender extends Handler {

        public CcMsgSender(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message m) {
            CcMsgStructure ccMsg = (CcMsgStructure) m.obj;
            HttpResponse resp = null;
            long time = System.currentTimeMillis()/1000;
            try {
                HttpPost httpPost = new HttpPost();
                switch (ccMsg.requestType){
                    case 1: // 号码簿api
                        httpPost.setURI(new URI(AsynHttpClient.HTTP_API_CLIENT + ccMsg.mApi));
                        break;
                    case 2: // 用户api
                        httpPost.setURI(new URI(AsynHttpClient.HTTP_API_USER_CLIENT + ccMsg.mApi));
                        break;
                    case 3: // 事件api
                        httpPost.setURI(new URI(AsynHttpClient.HTTP_API_EVENT_CLIENT + ccMsg.mApi));
                        break;
                    case 4: // 人脉圈 api
                        httpPost.setURI(new URI(AsynHttpClient.HTTP_API_TALK_CLIENT + ccMsg.mApi));
                        break;
                    case 5: // 融云聊天api
                        httpPost.setURI(new URI(AsynHttpClient.HTTP_API_RONG_CHAT_CLIENT + ccMsg.mApi));
                        break;
                    default:
                        break;
                }

                if ((ccMsg.requestType == 2 && ccMsg.type == 2) || ccMsg.requestType == 5){
                    // 登录、注册、忘记密码、获取验证码 接口不进行加密处理

                }else{
                    // SHA256加密处理
                    String security_key = PreferenceUtil.getInstance(mContext).getString("security_key","");
                    String api_key = LocalLogin.getInstance().mSid;
                    String key = __key__ + api_key;
                    String msg = api_key + security_key + time + ccMsg.mApi;
                    String sign = SHA256(key.getBytes(),msg.getBytes());

                    Log.d("My_Sign" , "key = " + key);
                    Log.d("My_Sign" , "msg = " + msg);
                    Log.d("My_Sign" , "sign = " + sign);

                    ccMsg.mParams.add(new BasicNameValuePair(AsynHttpClient.KEY_SIGN,sign));
                    ccMsg.mParams.add(new BasicNameValuePair(AsynHttpClient.KEY_TIMESTAMP,time + ""));
                    ccMsg.mParams.add(new BasicNameValuePair(AsynHttpClient.KEY_VERSION,"android/" + getVersionName(mContext)));
                }

                httpPost.setEntity(new UrlEncodedFormEntity(ccMsg.mParams, HTTP.UTF_8));
                httpPost.setHeader("User-Agent", String.format("%s (Linux; Android %s; %s Build/%s)", "ituandui.cn", Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));

                // 这是什么鬼？干啥的？
                if (ccMsg.type == CloudDialerActivity.CLOUD_SEARCH_MSG) {
                    CloudDialerActivity.sCloudSearch = CloudDialerActivity.CLOUD_SEARCH_SEND_OUT;
                }

                resp = sHttpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "CcMsgSender 1 ClientProtocolException: " + e.toString());
            } catch (UnsupportedEncodingException e) {
                Log.e(TAG, "CcMsgSender 1 UnsupportedEncodingException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 1 IOException: " + e.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            if (resp == null) {
                Log.e(TAG, "CcMsgSender HttpResponse is null, maybe no connection.");
                ccMsg.onError(ERROR_UNKNOWN, null);
                return;
            }

            boolean isRespOk = false;
            JSONObject respJson = null;
            int errorNum = ERROR_SERVER;
            try {
                String s = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                respJson = new JSONObject(s);
                errorNum = respJson.getInt(KEY_CC_CODE);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                      && errorNum == 0) {
                    isRespOk = true;
                }
            } catch (ParseException e) {
                Log.e(TAG, "CcMsgSender 2 ParseException: " + e.toString());
            } catch (JSONException e) {
                Log.e(TAG, "CcMsgSender 2 JSONException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 2 IOException: " + e.toString());
            }

            if (isRespOk) {
                ccMsg.onReceive(respJson);
            } else {
                ccMsg.onError(errorNum, respJson);
            }
        }
    }

    static class TalkMsgSender extends Handler {

        public TalkMsgSender(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message m) {
            CcMsgStructure ccMsg = (CcMsgStructure) m.obj;
            HttpResponse resp = null;
            try {
                HttpPost httpPost = new HttpPost();

                httpPost.setURI(new URI(AsynHttpClient.HTTP_API_TALK_CLIENT + ccMsg.mApi));
                httpPost.setEntity(new UrlEncodedFormEntity(ccMsg.mParams, HTTP.UTF_8));
                httpPost.setHeader("User-Agent", String.format("%s (Linux; Android %s; %s Build/%s)", "ituandui.cn", Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));

                if (ccMsg.type == CloudDialerActivity.CLOUD_SEARCH_MSG) {
                    CloudDialerActivity.sCloudSearch = CloudDialerActivity.CLOUD_SEARCH_SEND_OUT;
                }

                resp = sHttpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "CcMsgSender 1 ClientProtocolException: " + e.toString());
            } catch (UnsupportedEncodingException e) {
                Log.e(TAG, "CcMsgSender 1 UnsupportedEncodingException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 1 IOException: " + e.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            if (resp == null) {
                Log.e(TAG, "CcMsgSender HttpResponse is null, maybe no connection.");
                ccMsg.onError(ERROR_UNKNOWN, null);
                return;
            }


            boolean isRespOk = false;
            JSONObject respJson = null;
            int errorNum = ERROR_SERVER;
            try {
                String s = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                respJson = new JSONObject(s);
                errorNum = respJson.getInt(KEY_CC_CODE);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                      && errorNum == 0) {
                    isRespOk = true;
                }
            } catch (ParseException e) {
                Log.e(TAG, "CcMsgSender 2 ParseException: " + e.toString());
            } catch (JSONException e) {
                Log.e(TAG, "CcMsgSender 2 JSONException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 2 IOException: " + e.toString());
            }

            if (isRespOk) {
                ccMsg.onReceive(respJson);
            } else {
                ccMsg.onError(errorNum, respJson);
            }
        }
    }


    static class UserMsgSender extends Handler {

        public UserMsgSender(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message m) {
            CcMsgStructure ccMsg = (CcMsgStructure) m.obj;
            HttpResponse resp = null;
            try {
                HttpPost httpPost = new HttpPost();

                if (ccMsg.type == 1) {
                    httpPost.setURI(new URI(AsynHttpClient.HTTP_API_RONG_CHAT_CLIENT + ccMsg.mApi));
                } else {
                    httpPost.setURI(new URI(AsynHttpClient.HTTP_API_USER_CLIENT + ccMsg.mApi));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(ccMsg.mParams, HTTP.UTF_8));
                httpPost.setHeader("User-Agent", String.format("%s (Linux; Android %s; %s Build/%s)", "ituandui.cn", Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));

                if (ccMsg.type == CloudDialerActivity.CLOUD_SEARCH_MSG) {
                    CloudDialerActivity.sCloudSearch = CloudDialerActivity.CLOUD_SEARCH_SEND_OUT;
                }

                resp = sHttpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "CcMsgSender 1 ClientProtocolException: " + e.toString());
            } catch (UnsupportedEncodingException e) {
                Log.e(TAG, "CcMsgSender 1 UnsupportedEncodingException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 1 IOException: " + e.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            if (resp == null) {
                Log.e(TAG, "CcMsgSender HttpResponse is null, maybe no connection.");
                ccMsg.onError(ERROR_UNKNOWN, null);
                return;
            }

            boolean isRespOk = false;
            JSONObject respJson = null;
            int errorNum = ERROR_SERVER;
            try {
                String s = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                respJson = new JSONObject(s);
                errorNum = respJson.getInt(KEY_CC_CODE);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                      && errorNum == 0) {
                    isRespOk = true;
                }
            } catch (ParseException e) {
                Log.e(TAG, "CcMsgSender 2 ParseException: " + e.toString());
            } catch (JSONException e) {
                Log.e(TAG, "CcMsgSender 2 JSONException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 2 IOException: " + e.toString());
            }

            if (isRespOk) {
                ccMsg.onReceive(respJson);
            } else {
                ccMsg.onError(errorNum, respJson);
            }
        }
    }


    static class EventMsgSender extends Handler {

        public EventMsgSender(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message m) {
            CcMsgStructure ccMsg = (CcMsgStructure) m.obj;
            HttpResponse resp = null;
            try {
                HttpPost httpPost = new HttpPost();

                httpPost.setURI(new URI(AsynHttpClient.HTTP_API_EVENT_CLIENT + ccMsg.mApi));
                httpPost.setEntity(new UrlEncodedFormEntity(ccMsg.mParams, HTTP.UTF_8));
                httpPost.setHeader("User-Agent", String.format("%s (Linux; Android %s; %s Build/%s)", "ituandui.cn", Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));

                if (ccMsg.type == CloudDialerActivity.CLOUD_SEARCH_MSG) {
                    CloudDialerActivity.sCloudSearch = CloudDialerActivity.CLOUD_SEARCH_SEND_OUT;
                }

                resp = sHttpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "CcMsgSender 1 ClientProtocolException: " + e.toString());
            } catch (UnsupportedEncodingException e) {
                Log.e(TAG, "CcMsgSender 1 UnsupportedEncodingException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 1 IOException: " + e.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            if (resp == null) {
                Log.e(TAG, "CcMsgSender HttpResponse is null, maybe no connection.");
                ccMsg.onError(ERROR_UNKNOWN, null);
                return;
            }

            boolean isRespOk = false;
            JSONObject respJson = null;
            int errorNum = ERROR_SERVER;
            try {
                String s = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                respJson = new JSONObject(s);
                errorNum = respJson.getInt(KEY_CC_CODE);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                      && errorNum == 0) {
                    isRespOk = true;
                }
            } catch (ParseException e) {
                Log.e(TAG, "CcMsgSender 2 ParseException: " + e.toString());
            } catch (JSONException e) {
                Log.e(TAG, "CcMsgSender 2 JSONException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 2 IOException: " + e.toString());
            }

            if (isRespOk) {
                ccMsg.onReceive(respJson);
            } else {
                ccMsg.onError(errorNum, respJson);
            }
        }
    }



    class HttpsMsgSender extends Handler {

        public HttpsMsgSender(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message m) {
            CcMsgStructure ccMsg = (CcMsgStructure) m.obj;
            InputStream ins = null;
            String result = "";
            HttpResponse resp = null;
            try {
                ins = mContext.getAssets().open("certificate.crt"); // 下载的证书放到项目中的assets目录中
                CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
                Certificate cer = cerFactory.generateCertificate(ins);
                KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
                keyStore.load(null, null);
                keyStore.setCertificateEntry("trust", cer);

                SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore);
                Scheme sch = new Scheme("https", socketFactory, 443);
                HttpClient mHttpClient = new DefaultHttpClient();
                mHttpClient.getConnectionManager().getSchemeRegistry().register(sch);

                BufferedReader reader = null;
                try {
                    HttpPost httpPost = new HttpPost();
                    httpPost.setURI(new URI(AsynHttpClient.HTTPS_API_USER_CLIENT + ccMsg.mApi));
                    httpPost.setEntity(new UrlEncodedFormEntity(ccMsg.mParams, HTTP.UTF_8));
                    if (ccMsg.type == CloudDialerActivity.CLOUD_SEARCH_MSG) {
                        CloudDialerActivity.sCloudSearch = CloudDialerActivity.CLOUD_SEARCH_SEND_OUT;
                    }

                    resp = sHttpclient.execute(httpPost);

                    reader = new BufferedReader(new InputStreamReader(resp
                          .getEntity().getContent()));
                    StringBuffer buffer = new StringBuffer();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line);
                    }
                    result = buffer.toString();
                    Log.d("My_Https",result);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }

                if (resp == null) {
                    Log.e(TAG, "CcMsgSender HttpResponse is null, maybe no connection.");
                    ccMsg.onError(ERROR_UNKNOWN, null);
                    return;
                }

                boolean isRespOk = false;
                JSONObject respJson = null;
                int errorNum = ERROR_SERVER;
                try {
                    String s = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                    respJson = new JSONObject(s);
                    errorNum = respJson.getInt(KEY_CC_CODE);
                    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                          && errorNum == 0) {
                        isRespOk = true;
                    }
                } catch (ParseException e) {
                    Log.e(TAG, "CcMsgSender 2 ParseException: " + e.toString());
                } catch (JSONException e) {
                    Log.e(TAG, "CcMsgSender 2 JSONException: " + e.toString());
                } catch (IOException e) {
                    Log.e(TAG, "CcMsgSender 2 IOException: " + e.toString());
                }

                if (isRespOk) {
                    ccMsg.onReceive(respJson);
                } else {
                    ccMsg.onError(errorNum, respJson);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (ins != null)
                        ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    static class CRMMsgSender extends Handler {

        public CRMMsgSender(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message m) {
            CcMsgStructure ccMsg = (CcMsgStructure) m.obj;
            HttpResponse resp = null;
            try {
                HttpPost httpPost = new HttpPost();

                httpPost.setURI(new URI(AsynHttpClient.HTTP_API_CRM_CLIENT + ccMsg.mApi));
                httpPost.setEntity(new UrlEncodedFormEntity(ccMsg.mParams, HTTP.UTF_8));
                httpPost.setHeader("User-Agent", String.format("%s (Linux; Android %s; %s Build/%s)", "ituandui.cn", Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));
                // httpPost.setHeader("User-Agent", String.format("%s/%s (Linux; Android %s; %s Build/%s)", MY_APP_NAME, MY_APP_VERSION_NAME, Build.VERSION.RELEASE, Build.MANUFACTURER, Build.ID));
                if (ccMsg.type == CloudDialerActivity.CLOUD_SEARCH_MSG) {
                    CloudDialerActivity.sCloudSearch = CloudDialerActivity.CLOUD_SEARCH_SEND_OUT;
                }

                resp = sHttpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "CcMsgSender 1 ClientProtocolException: " + e.toString());
            } catch (UnsupportedEncodingException e) {
                Log.e(TAG, "CcMsgSender 1 UnsupportedEncodingException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 1 IOException: " + e.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            if (resp == null) {
                Log.e(TAG, "CcMsgSender HttpResponse is null, maybe no connection.");
                ccMsg.onError(ERROR_UNKNOWN, null);
                return;
            }

            boolean isRespOk = false;
            JSONObject respJson = null;
            int errorNum = ERROR_SERVER;
            try {
                String s = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                respJson = new JSONObject(s);
                errorNum = respJson.getInt(KEY_CC_CODE);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                      && errorNum == 0) {
                    isRespOk = true;
                }
            } catch (ParseException e) {
                Log.e(TAG, "CcMsgSender 2 ParseException: " + e.toString());
            } catch (JSONException e) {
                Log.e(TAG, "CcMsgSender 2 JSONException: " + e.toString());
            } catch (IOException e) {
                Log.e(TAG, "CcMsgSender 2 IOException: " + e.toString());
            }

            if (isRespOk) {
                ccMsg.onReceive(respJson);
            } else {
                ccMsg.onError(errorNum, respJson);
            }
        }
    }

    /**
     * 获取hash值的签名
     * @param key
     * @param msg
     */
    public static String SHA256(byte[] key, byte[] msg) {
        String Algor = "HmacSHA256";
        Mac localMac = null;
        String sign = "";
        try {
            localMac = Mac.getInstance(Algor);
            localMac.init(new SecretKeySpec(key, Algor));
            msg = localMac.doFinal(msg);
            sign = Base64.encodeToString(msg, Base64.NO_WRAP);
            Log.d("Signature", Base64.encodeToString(msg, Base64.NO_WRAP));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }


}
